# -*- coding: utf-8 -*-
'''
@File    :   edgeTTS.py
@Author  :   一力辉 
'''

from ..builder import TTSEngines
from ..engineBase import BaseEngine
import edge_tts
from io import BytesIO
from typing import List, Optional
from pydub import AudioSegment
from digitalHuman.utils import logger
from digitalHuman.utils import TextMessage, AudioMessage, AudioFormatType

import dashscope
from dashscope.audio.tts_v2 import *

__all__ = ["AliAPI"]


def mp3ToWav(mp3Bytes: bytes) -> bytes:
    mp3Data = BytesIO(mp3Bytes)
    audio = AudioSegment.from_mp3(mp3Data)
    wavData = BytesIO()
    audio.export(wavData, format="wav")
    wavBytes = wavData.getvalue()
    return wavBytes


@TTSEngines.register("AliAPI")
class AliAPI(BaseEngine):
    def checkKeys(self) -> List[str]:
        return ["KEY", "MODEL", "VOICE"]

    async def run(self, input: TextMessage, **kwargs) -> Optional[TextMessage]:
        print("-------------------对话答案阿里云文字转语音----------------------------")
        try:
            dashscope.api_key = self.cfg.KEY
            synthesizer = SpeechSynthesizer(model=self.cfg.MODEL, voice=self.cfg.VOICE)
            logger.info(f"调用TTS： {input.data}")
            audio = synthesizer.call(input.data)
            # mp3 -> wav
            data = mp3ToWav(audio)
            message = AudioMessage(
                data=data,
                desc=input.data,
                format=AudioFormatType.WAV,
                sampleRate=16000,
                sampleWidth=2,
            )
            return message
        except Exception as e:
            logger.error(f"[TTS] Engine run failed: {e}")
            return None
